﻿using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;

namespace Snake.Utils
{
   public static class ExpressionHelper
    {
        /// <summary>
        /// 根据表达式获取属性 如a=>a.ID 获取到ID这个属性
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        public static PropertyInfo GetPropertyInfo(LambdaExpression expr)
        {
            return (PropertyInfo)((MemberExpression)expr.Body).Member;
        }

        /// <summary>
        /// 干掉表达式目录树中的引用类型
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static Expression StripQuotes(Expression e)
        {
            while (e.NodeType == ExpressionType.Quote)
            {
                e = ((UnaryExpression)e).Operand;
            }
            return e;
        }  

        /// <summary>
        /// 获取lambda表达式
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static LambdaExpression GetLambda(Expression e)
        {
            return StripQuotes(e) as LambdaExpression;
        }
        
        /// <summary>
        /// 获取属性路径
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        public static PropertyInfo[] GetPropertyPath(Expression expr)
        {
            var path = new Stack<PropertyInfo>();

            while (expr.NodeType == ExpressionType.MemberAccess)
            {
                var mexpr = (MemberExpression)expr;
                var propInfo = mexpr.Member as PropertyInfo;
                if (propInfo == null)
                    break;

                path.Push(propInfo);
                expr = mexpr.Expression;
            }

            return path.ToArray();
        }
    }
}
